import React, { useState, useEffect } from 'react';
import { Input, Tabs, Avatar, Empty, Spin, Button, Alert, message } from 'antd';
import { SearchOutlined, ExclamationCircleOutlined, LinkOutlined } from '@ant-design/icons';
import { useWebsites } from '../context/WebsiteContext';

const { Search } = Input;

const SearchPage = () => {
  const { websites } = useWebsites();

  // 过滤掉已禁用的网站
  const enabledWebsites = websites.filter(website => !website.disabled);
  const [keyword, setKeyword] = useState('');
  const [inputValue, setInputValue] = useState('');
  const [searchTabs, setSearchTabs] = useState([]);
  const [activeTab, setActiveTab] = useState('');
  const [loading, setLoading] = useState(false);
  const [iframeErrors, setIframeErrors] = useState(new Set());
  const [iframeKey, setIframeKey] = useState(0); // 用于强制刷新iframe

  useEffect(() => {
    if (enabledWebsites.length > 0) {
      // 根据是否有搜索关键词来决定显示内容
      const tabs = enabledWebsites.map(website => ({
        ...website,
        searchResultUrl: keyword
          ? website.searchUrl.replace('{keyword}', encodeURIComponent(keyword.trim()))
          : website.url // 没有搜索关键词时使用首页URL
      }));
      setSearchTabs(tabs);

      if (!activeTab || !enabledWebsites.find(w => w.id === activeTab)) {
        setActiveTab(enabledWebsites[0].id);
      }

      // 预先标记已知会拒绝连接的网站
      const knownProblematicDomains = ['anime1.me', 'gimy.ai'];
      const problematicTabs = new Set();
      tabs.forEach(tab => {
        const domain = new URL(tab.searchResultUrl).hostname;
        if (knownProblematicDomains.some(problematic => domain.includes(problematic))) {
          problematicTabs.add(tab.id);
        }
      });

      if (problematicTabs.size > 0) {
        setIframeErrors(prev => new Set([...prev, ...problematicTabs]));
      }
    }
  }, [enabledWebsites, keyword, activeTab]);

  const handleIframeError = (tabId) => {
    setIframeErrors(prev => new Set([...prev, tabId]));
  };

  const openInNewTab = (url) => {
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  const resetIframeError = (tabId) => {
    setIframeErrors(prev => {
      const newSet = new Set(prev);
      newSet.delete(tabId);
      return newSet;
    });
  };

  const clearSearch = () => {
    setKeyword('');
    setInputValue('');
    setIframeErrors(new Set());
    // 清除关键词后，useEffect会自动重置为首页
  };

  const handleSearch = async (searchKeyword) => {
    if (!searchKeyword.trim()) return;

    setLoading(true);
    setKeyword(searchKeyword);
    setIframeErrors(new Set()); // 重置错误状态
    setIframeKey(prev => prev + 1); // 强制刷新所有iframe

    console.log('搜索关键词:', searchKeyword);

    // 模拟加载延迟
    setTimeout(() => {
      setLoading(false);
    }, 500);
  };

  const tabItems = searchTabs.map(tab => ({
    label: (
      <span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
        <Avatar
          src={tab.icon}
          size={24}
          style={{ backgroundColor: '#f0f0f0' }}
        >
          {tab.name.charAt(0)}
        </Avatar>
        <span>{tab.name}</span>
        {iframeErrors.has(tab.id) && (
          <ExclamationCircleOutlined style={{ color: '#ff4d4f', fontSize: '12px' }} />
        )}
      </span>
    ),
    key: tab.id,
    children: null // 我们将在下面单独渲染内容
  }));

  if (enabledWebsites.length === 0) {
    return (
      <div style={{
        padding: '48px',
        textAlign: 'center',
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center'
      }}>
        <Empty
          description={websites.length === 0 ? "暂无影视网站" : "暂无可用的影视网站"}
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        >
          <p style={{ color: '#666', marginTop: '16px' }}>
            {websites.length === 0
              ? "请先到管理页面添加影视网站"
              : "所有网站都已被禁用，请到管理页面启用网站"
            }
          </p>
        </Empty>
      </div>
    );
  }

  return (
    <div style={{
      padding: '24px',
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    }}>
      {/* 搜索区域 */}
      <div style={{
        textAlign: 'center',
        marginBottom: '32px',
        paddingTop: '40px'
      }}>
        <h1 style={{
          color: '#fff',
          fontSize: '32px',
          marginBottom: '32px',
          textShadow: '0 2px 4px rgba(0,0,0,0.3)'
        }}>
          影视资源搜索
        </h1>

        <div style={{
          maxWidth: '600px',
          margin: '0 auto',
          animation: 'slideInUp 0.6s ease-out'
        }}>
          <Search
            placeholder="输入电影或电视剧名称..."
            enterButton={
              <span>
                <SearchOutlined /> 搜索
              </span>
            }
            size="large"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onSearch={handleSearch}
            onClear={clearSearch}
            style={{
              fontSize: '16px',
            }}
            allowClear
          />
        </div>

        {keyword ? (
          <p style={{
            color: '#fff',
            marginTop: '16px',
            fontSize: '16px',
            opacity: 0.9
          }}>
            搜索关键词：<strong>"{keyword}"</strong>
          </p>
        ) : (
          <p style={{
            color: '#fff',
            marginTop: '16px',
            fontSize: '16px',
            opacity: 0.8
          }}>
            浏览各大影视网站首页，或输入关键词开始搜索
          </p>
        )}
      </div>

      {/* 网站展示区域 */}
      {searchTabs.length > 0 && (
        <div style={{
          backgroundColor: '#fff',
          borderRadius: '12px',
          padding: '24px',
          boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
          animation: 'fadeInUp 0.5s ease-out'
        }}>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            type="card"
            size="large"
            items={tabItems}
            tabBarStyle={{
              marginBottom: '16px',
              borderBottom: '1px solid #f0f0f0'
            }}
          />

          {/* iframe容器 - 所有iframe同时存在，通过显示/隐藏切换 */}
          <div style={{
            height: 'calc(100vh - 200px)',
            border: '1px solid #d9d9d9',
            borderRadius: '6px',
            overflow: 'hidden',
            backgroundColor: '#fff',
            position: 'relative'
          }}>
            {loading ? (
              <div style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100%',
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: '#fff',
                zIndex: 10
              }}>
                <Spin size="large" tip="加载搜索结果中..." />
              </div>
            ) : (
              searchTabs.map(tab => (
                <div
                  key={tab.id}
                  style={{
                    width: '100%',
                    height: '100%',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    display: activeTab === tab.id ? 'block' : 'none',
                  }}
                >
                  {iframeErrors.has(tab.id) ? (
                    // 显示错误提示和备用方案
                    <div style={{
                      display: 'flex',
                      flexDirection: 'column',
                      justifyContent: 'center',
                      alignItems: 'center',
                      height: '100%',
                      padding: '40px',
                      textAlign: 'center'
                    }}>
                      <Alert
                        message="无法在框架中加载此网站"
                        description={
                          <div>
                            <p>{`${tab.name} 拒绝连接或禁止在iframe中显示内容。`}</p>
                            <p>这可能是由于网站的安全设置（如 X-Frame-Options 或 CSP 策略）导致的。</p>
                          </div>
                        }
                        type="warning"
                        icon={<ExclamationCircleOutlined />}
                        style={{ marginBottom: '24px', maxWidth: '500px' }}
                      />

                      <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', justifyContent: 'center' }}>
                        <Button
                          type="primary"
                          icon={<LinkOutlined />}
                          onClick={() => openInNewTab(tab.searchResultUrl)}
                          size="large"
                        >
                          在新标签页中打开
                        </Button>

                        <Button
                          onClick={() => resetIframeError(tab.id)}
                          size="large"
                        >
                          重试加载
                        </Button>

                        <Button
                          onClick={() => {
                            navigator.clipboard.writeText(tab.searchResultUrl);
                            message.success('链接已复制到剪贴板');
                          }}
                          size="large"
                        >
                          复制链接
                        </Button>
                      </div>

                      <p style={{
                        marginTop: '16px',
                        color: '#666',
                        fontSize: '14px'
                      }}>
                        链接：{tab.searchResultUrl}
                      </p>
                    </div>
                  ) : (
                    <>
                      <iframe
                        key={`${tab.id}-${iframeKey}`}
                        src={tab.searchResultUrl}
                        style={{
                          width: '100%',
                          height: '100%',
                          border: 'none',
                          transition: 'opacity 0.2s ease-in-out'
                        }}
                        sandbox="allow-same-origin allow-scripts allow-forms allow-popups"
                        title={`${tab.name}-搜索结果`}
                        loading="lazy"
                        onError={() => handleIframeError(tab.id)}
                      />

                      {/* 浮动的操作按钮 */}
                      {activeTab === tab.id && (
                        <div style={{
                          position: 'absolute',
                          top: '10px',
                          right: '10px',
                          zIndex: 5,
                          display: 'flex',
                          gap: '8px'
                        }}>
                          <Button
                            size="small"
                            type="text"
                            icon={<LinkOutlined />}
                            onClick={() => openInNewTab(tab.searchResultUrl)}
                            style={{
                              backgroundColor: 'rgba(24, 144, 255, 0.9)',
                              color: '#fff',
                              border: 'none',
                              fontSize: '12px'
                            }}
                            title="在新标签页中打开"
                          >
                            新标签页
                          </Button>
                          {/* <Button
                            size="small"
                            type="text"
                            onClick={() => handleIframeError(tab.id)}
                            style={{
                              backgroundColor: 'rgba(255, 255, 255, 0.9)',
                              border: '1px solid #d9d9d9',
                              fontSize: '12px'
                            }}
                            title="报告加载问题"
                          >
                            无法加载？
                          </Button> */}
                        </div>
                      )}
                    </>
                  )}
                </div>
              ))
            )}
          </div>
        </div>
      )}

      <style jsx>{`
        @keyframes slideInUp {
          from {
            opacity: 0;
            transform: translateY(30px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
        
        @keyframes fadeInUp {
          from {
            opacity: 0;
            transform: translateY(20px);
          }
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}</style>
    </div>
  );
};

export default SearchPage;